#!/usr/bin/python
# -*- coding: utf-8 -*-
# AUTHOR:   guangling.hou@gmail.com
# FILENAME: py_json.py
# CREATED:  14:08:04 10/12/2012
# MODIFIED: 2014-02-08 13:56

import json
from dm_py_util import *

class PYC_JsonParser():
	def __init__(self):
		#输出的decode直接就是unicode编码的 要想使用还需要转成utf-8编码的
		self.decoder = json.JSONDecoder(encoding='utf-8')
		self.encoder = json.JSONEncoder(encoding = 'utf-8',
										#其他编码的不会被转成unicode
										ensure_ascii = False)

	def encodeJson(self,obj):
		try:
			str = self.encoder.encode(obj)
			return str
		except:
			raise DM_InputError('json编码错误')

	def decodeJson(self,jsonstr):
		if isinstance(jsonstr,unicode) is not True:
			raise DM_InputError('输入字符串不是unicode')
		try:
			res = self.decoder.decode(jsonstr.encode('utf-8'))
			return res
		except:
			raise DM_InputError('输入json错误')



if __name__ == '__main__':

	decoder = PY_Decode()
	httpclient = PYC_HttpClient()						

	"""
	url = 'http://192.168.10.152:1668/newlist/playlistcontainer/log?|cc=TG60392&cn=&conn=3G&cv=DM5.0.0.00_I3.0&devi=3b27fdc4c47b855e0a8b723b5965b57a8fa21783&devmd5=ddd9a887ba2d360380712e16c821dea5&imei=&imsi=&islogin=1&licenseid=69D63DE5F8BB63B2&rid=2193109978321783&session=0GNOAgXHYewVi2L70oSj3HkAi3&ua=iPhone&uid=10346697&validation=3421584652&version=0'
	uri = decoder.decode(url)
	response = httpclient.request(uri)
	print response,type(response) #返回的是字节码
	"""

	uri = "http://192.168.2.107:7035/sdj/room/active?room_id=2"
	uri = uri.decode('utf-8')
	response = httpclient.request(Uri = uri,
					Timeout = 1)
	print response,type(response) #返回的是字节码


	jsonp = PYC_JsonParser()
	res = jsonp.decodeJson(response)
	print "real_result",res,type(res)
	print res["room"]["announcement"],type(res["room"]["announcement"])

	print res["room"]["announcement"].encode('utf-8')


	print "\n-----------------------------------------------------"
	try:
		en_res = jsonp.encodeJson(res)
		print en_res,type(en_res)
	except Exception,e:
		print str(e)
